package com.ruicar.afs.cloud.afscase.loanapprove.task.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.Console;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.afscase.approvemakelabel.entity.LoanLabelInfo;
import com.ruicar.afs.cloud.afscase.approvemakelabel.service.LoanLabelInfoService;
import com.ruicar.afs.cloud.afscase.approvetask.entity.CaseApproveRecord;
import com.ruicar.afs.cloud.afscase.approvetask.entity.WorkTaskPool;
import com.ruicar.afs.cloud.afscase.approvetask.service.CaseApproveRecordService;
import com.ruicar.afs.cloud.afscase.approvetask.service.WorkTaskPoolService;
import com.ruicar.afs.cloud.afscase.approvetask.vo.ApproveTaskVo;
import com.ruicar.afs.cloud.afscase.approvetask.vo.TaskHandlerChangeVO;
import com.ruicar.afs.cloud.afscase.channel.entity.ChannelBaseInfo;
import com.ruicar.afs.cloud.afscase.channel.service.ChannelBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCarInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseChannelInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseContractInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseBaseInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseCarInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseChannelInfoService;
import com.ruicar.afs.cloud.afscase.infomanagement.service.CaseContractInfoService;
import com.ruicar.afs.cloud.afscase.loanactivatepool.entity.LoanActivatePool;
import com.ruicar.afs.cloud.afscase.loanactivatepool.service.LoanActivateService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.LoanApproveService;
import com.ruicar.afs.cloud.afscase.loanapprove.service.LoanWorkflowService;
import com.ruicar.afs.cloud.afscase.loanapprove.task.condition.LoanApproveTaskCondition;
import com.ruicar.afs.cloud.afscase.loanapprove.task.service.LoanApproveTaskService;
import com.ruicar.afs.cloud.afscase.loanapprove.task.vo.LoanApproveTaskVO;
import com.ruicar.afs.cloud.afscase.manuallabel.entity.ManualLabel;
import com.ruicar.afs.cloud.afscase.manuallabel.service.ManualLabelService;
import com.ruicar.afs.cloud.afscase.mq.approvesendinfo.service.ApproveLoanInfoService;
import com.ruicar.afs.cloud.afscase.processor.service.LoanApproveWorkflowService;
import com.ruicar.afs.cloud.afscase.processor.vo.NormalReformistVO;
import com.ruicar.afs.cloud.afscase.risk.service.CaseTortoiseService;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.*;
import com.ruicar.afs.cloud.risk.api.enums.tortoise.GwtTortoiseAntiFraudCallStep;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>Description:放款审核待办任务相关</p>
 *
 * @author xueyu.ma
 * @Version 1.0
 * @CreateDate 2020-5-29
 */

@Slf4j
@RestController
@AllArgsConstructor
@Api("放款审核待办任务")
@RequestMapping("/loanApproveTask")
public class LoanApproveTaskController {

    private final LoanApproveTaskService loanApproveTaskService;
    private final CaseChannelInfoService caseChannelInfoService;
    private CaseApproveRecordService caseApproveRecordService;
    private CaseCarInfoService caseCarInfoService;
    private CaseBaseInfoService caseBaseInfoService;
    private LoanLabelInfoService loanLabelInfoService;
    private CaseContractInfoService caseContractInfoService;
    private LoanApproveWorkflowService loanApproveWorkflowService;
    private LoanApproveService loanApproveService;
    private LoanActivateService loanActivateService;
    private ApproveLoanInfoService approveLoanInfoService;
    private LoanWorkflowService loanWorkflowService;
    private CaseTortoiseService caseTortoiseService;
    private final ManualLabelService manualLabelService;
    private WorkTaskPoolService workTaskPoolService;

    @PostMapping("/getLoanApproveTaskList")
    @ApiOperation(value = "多条件获取放款初审待办任务列表")
    public IResponse<List<LoanApproveTaskVO>> queryLoanApproveTaskList(@RequestBody LoanApproveTaskCondition loanApproveTaskCondition) {
        String userName = SecurityUtils.getUsername();
        loanApproveTaskCondition.setApproveStaff(userName);
        if(loanApproveTaskCondition.getStartDate()!=null){
            LocalDateTime startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(loanApproveTaskCondition.getStartDate().getTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(loanApproveTaskCondition.getEndDate().getTime()), ZoneId.systemDefault());
            //获取最小时间 xxxx-xx-xx 0:00:00
            LocalDateTime startOfDay = startTime.with(LocalTime.MIN);
            log.info("获取范围最小时间{}",startOfDay);
            //获取30天前最大时间 xxxx-xx-xx 23:59:59
            LocalDateTime endOfDay = endTime.with(LocalTime.MAX);
            log.info("获取范围最大时间{}",endOfDay);
            loanApproveTaskCondition.setStartDate(Date.from(startOfDay.atZone( ZoneId.systemDefault()).toInstant()));
            loanApproveTaskCondition.setEndDate(Date.from(endOfDay.atZone( ZoneId.systemDefault()).toInstant()));
        }
        //流程类型：放款常规审批流程
        List<String> loanWorkflowTypeList = new ArrayList<>();
        List<String> applyStatusList = new ArrayList<>();
        loanWorkflowTypeList.add(LoanProcessTypeEnum.GENERAL_LOAN.getCode());
        applyStatusList.add(ApplyStatusEnum.LOAN_WAIT_APPROVE.getState());
        applyStatusList.add(ApplyStatusEnum.LOAN_WAIT_CONFIRM.getState());
        applyStatusList.add(ApplyStatusEnum.LOAN_REVIEW_RETURN.getState());
        applyStatusList.add(ApplyStatusEnum.SUSPEND_WAIT.getState());
        applyStatusList.add(ApplyStatusEnum.LOAN_REPAIR.getState());
        loanApproveTaskCondition.setApplyStatusList(applyStatusList);
        loanApproveTaskCondition.setProcessTypeList(loanWorkflowTypeList);
        Page page = new Page(loanApproveTaskCondition.getPageNumber(), loanApproveTaskCondition.getPageSize());
        IPage<LoanApproveTaskVO> loanApproveTaskVOList = loanApproveTaskService.getLoanApproveTaskVOList(page, loanApproveTaskCondition);
        loanApproveTaskVOList.getRecords().forEach(vo -> {
            /** 案件渠道信息 */
//            CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
//                    .eq(CaseChannelInfo::getApplyNo, vo.getApplyNo()), false);
//            if (caseChannelInfo != null) {
//                /**渠道基本信息*/
//                ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda()
//                        .eq(ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()));
//                vo.setIsOverdue(channelBaseInfo != null ? channelBaseInfo.getIsOverdue() : WhetherEnum.NO.getCode());
//            }
            /**标签信息表**/
            List<LoanLabelInfo> labelList = loanLabelInfoService.list(Wrappers.<LoanLabelInfo>query().lambda()
                    .eq(LoanLabelInfo::getApplyNo, vo.getApplyNo())
                    .eq(LoanLabelInfo::getContractNo, vo.getContractNo()));
            vo.setLabelList(labelList);

        });
        return IResponse.success(loanApproveTaskVOList);
    }

    @PostMapping("/getloanDealWithTaskList")
    @ApiOperation(value = "多条件获取放款初审待办任务列表")
    public IResponse<List<LoanApproveTaskVO>> queryloanDealWithTaskList(@RequestBody LoanApproveTaskCondition loanApproveTaskCondition) {
        String userName = SecurityUtils.getUsername();
        loanApproveTaskCondition.setApproveStaff(userName);
        if(loanApproveTaskCondition.getStartDate()!=null){
            LocalDateTime startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(loanApproveTaskCondition.getStartDate().getTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(loanApproveTaskCondition.getEndDate().getTime()), ZoneId.systemDefault());
            //获取最小时间 xxxx-xx-xx 0:00:00
            LocalDateTime startOfDay = startTime.with(LocalTime.MIN);
            log.info("获取范围最小时间{}",startOfDay);
            //获取最大时间 xxxx-xx-xx 23:59:59
            LocalDateTime endOfDay = endTime.with(LocalTime.MAX);
            log.info("获取范围最大时间{}",endOfDay);
            loanApproveTaskCondition.setStartDate(Date.from(startOfDay.atZone( ZoneId.systemDefault()).toInstant()));
            loanApproveTaskCondition.setEndDate(Date.from(endOfDay.atZone( ZoneId.systemDefault()).toInstant()));
        }
        if(loanApproveTaskCondition.getStartDate2()!=null){
            LocalDateTime startDate2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(loanApproveTaskCondition.getStartDate2().getTime()), ZoneId.systemDefault());
            LocalDateTime endDate2 = LocalDateTime.ofInstant(Instant.ofEpochMilli(loanApproveTaskCondition.getEndDate2().getTime()), ZoneId.systemDefault());
            LocalDateTime startOfDay2 = startDate2.with(LocalTime.MIN);
            log.info("获取范围最小时间{}",startOfDay2);
            //获取最大时间 xxxx-xx-xx 23:59:59
            LocalDateTime endOfDay2 = endDate2.with(LocalTime.MAX);
            log.info("获取范围最大时间{}",endOfDay2);
            loanApproveTaskCondition.setStartDate2(Date.from(startOfDay2.atZone( ZoneId.systemDefault()).toInstant()));
            loanApproveTaskCondition.setEndDate2(Date.from(endOfDay2.atZone( ZoneId.systemDefault()).toInstant()));
        }
        //流程类型：放款常规审批流程
        List<String> loanWorkflowTypeList = new ArrayList<>();
        loanWorkflowTypeList.add(LoanProcessTypeEnum.GENERAL_LOAN.getCode());
        loanWorkflowTypeList.add(LoanProcessTypeEnum.LOAN_REPAIR.getCode());
        loanWorkflowTypeList.add(LoanProcessTypeEnum.FLAW_UPDATE.getCode());
        loanWorkflowTypeList.add(LoanProcessTypeEnum.INSPECTION.getCode());
        loanWorkflowTypeList.add(LoanProcessTypeEnum.GPS_AUDIT.getCode());
        loanApproveTaskCondition.setProcessTypeList(loanWorkflowTypeList);
        Page page = new Page(loanApproveTaskCondition.getPageNumber(), loanApproveTaskCondition.getPageSize());
        IPage<LoanApproveTaskVO> loanApproveTaskVOList = loanApproveTaskService.getloanDealWithTaskList(page, loanApproveTaskCondition);
        loanApproveTaskVOList.getRecords().forEach(vo -> {
            /** 案件渠道信息 */
//            CaseChannelInfo caseChannelInfo = caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
//                    .eq(CaseChannelInfo::getApplyNo, vo.getApplyNo()), false);
//            if (caseChannelInfo != null) {
//                /**渠道基本信息*/
//                ChannelBaseInfo channelBaseInfo = channelBaseInfoService.getOne(Wrappers.<ChannelBaseInfo>query().lambda()
//                        .eq(ChannelBaseInfo::getChannelCode, caseChannelInfo.getDealerNo()));
//                vo.setIsOverdue(channelBaseInfo != null ? channelBaseInfo.getIsOverdue() : WhetherEnum.NO.getCode());
//            }
            /**标签信息表**/
            List<LoanLabelInfo> labelList = loanLabelInfoService.list(Wrappers.<LoanLabelInfo>query().lambda()
                    .eq(LoanLabelInfo::getApplyNo, vo.getApplyNo())
                    .eq(LoanLabelInfo::getContractNo, vo.getContractNo()));
            vo.setLabelList(labelList);

        });
        if (StringUtils.isNotBlank(loanApproveTaskCondition.getChannelType())) {
            List<LoanApproveTaskVO> loanApproveTaskVOResult = loanApproveTaskVOList.getRecords().stream()
                    .filter(LoanApproveTaskVO -> loanApproveTaskCondition.getChannelType().equals(LoanApproveTaskVO.getChannelType()))
                    .collect(Collectors.toList());
            loanApproveTaskVOList.getRecords().clear();
            loanApproveTaskVOList.setRecords(loanApproveTaskVOResult);
        }
        return IResponse.success(loanApproveTaskVOList);
    }

    @PostMapping("/getLoanReviewTaskList")
    @ApiOperation(value = "多条件获取放款复审待办任务列表")
    public IResponse<List<LoanApproveTaskVO>> queryLoanReviewTaskList(@RequestBody LoanApproveTaskCondition loanApproveTaskCondition) {
        String userId = SecurityUtils.getUsername();
        loanApproveTaskCondition.setApproveStaff(userId);
        //流程类型：放款常规审批流程
        List<String> loanWorkflowTypeList = new ArrayList<>();
        List<String> applyStatusList = new ArrayList<>();
        loanWorkflowTypeList.add(LoanProcessTypeEnum.GENERAL_LOAN.getCode());
        applyStatusList.add(ApplyStatusEnum.LOAN_WAIT_CONFIRM.getState());
        loanApproveTaskCondition.setApplyStatusList(applyStatusList);
        loanApproveTaskCondition.setProcessTypeList(loanWorkflowTypeList);
        Page page = new Page(loanApproveTaskCondition.getPageNumber(), loanApproveTaskCondition.getPageSize());
        IPage<LoanApproveTaskVO> loanApproveTaskVOList = loanApproveTaskService.getLoanApproveTaskVOList(page, loanApproveTaskCondition);
        if (StringUtils.isNotBlank(loanApproveTaskCondition.getChannelType())) {
            List<LoanApproveTaskVO> loanApproveTaskVOResult = loanApproveTaskVOList.getRecords().stream()
                    .filter(LoanApproveTaskVO -> loanApproveTaskCondition.getChannelType().equals(LoanApproveTaskVO.getChannelType()))
                    .collect(Collectors.toList());
            loanApproveTaskVOList.getRecords().clear();
            loanApproveTaskVOList.setRecords(loanApproveTaskVOResult);
        }
//        long pages = loanApproveTaskVOList.getRecords().size() / loanApproveTaskVOList.getSize();
//        if (loanApproveTaskVOList.getRecords().size() % loanApproveTaskVOList.getSize() != 0L) {
//            ++pages;
//        }
//        loanApproveTaskVOList.setTotal(loanApproveTaskVOList.getRecords().size());
//        loanApproveTaskVOList.setPages(pages);
        return IResponse.success(loanApproveTaskVOList);
    }


    @PostMapping("/modifyLock")
    @ApiOperation("更改案件锁定状态")
    @Transactional(rollbackFor = Exception.class)
    public IResponse modifyLock(@RequestParam("data") String jsonDataArrStr,
                                @RequestParam("lockRemark") String lockRemark,
                                @RequestParam("status") String status) {
        String[] str = jsonDataArrStr.split(",");
        List contractNoList = new ArrayList();
        for (int i = 0; i < str.length; i++) {
            contractNoList.add(str[i]);
        }
        // 保存锁定、解除锁定操作备注信息

        for (int i = 0; i < contractNoList.size(); i++) {
            //LockEnum lockEnum = LockEnum.LOCK;
            if (WhetherEnum.YES.getCode().equals(status)) {
                loanApproveService.lockContract(contractNoList.get(i).toString(),lockRemark);
            }else{
                loanApproveService.unLockContract(contractNoList.get(i).toString(),lockRemark);
            }

            log.info("************************案件锁定状态修改成功*******************************");
        }
        return IResponse.success("操作成功");
    }

    @PostMapping("/modifyTop")
    @ApiOperation("更改案件置顶状态")
    @Transactional(rollbackFor = Exception.class)
    public IResponse modifyTop(@RequestParam("data") String jsonDataArrStr, @RequestParam("status") String status) {
        String[] str = jsonDataArrStr.split(",");
        List contractNoList = new ArrayList();
        for (int i = 0; i < str.length; i++) {
            contractNoList.add(str[i]);
        }
        return IResponse.success(loanApproveTaskService.modifyTop(contractNoList, status));
    }

    @PostMapping("/delLabelList")
    @ApiOperation("删除案件标签")
    @Transactional(rollbackFor = Exception.class)
    public IResponse delLabelList(@RequestParam("data") String jsonDataArrStr){
        String[] str=jsonDataArrStr.split(",");
        List contractNoList=new ArrayList();
        for(int i=0;i<str.length;i++){
            contractNoList.add(str[i]);
        }
        if(CollectionUtils.isNotEmpty(contractNoList)){
            loanApproveTaskService.delLabelList(contractNoList);
        }
        log.info("************************案件标签删除成功*******************************");
        return IResponse.success("操作成功");
    }

    @PostMapping("/modifyLabel")
    @ApiOperation("更改案件标签")
    @Transactional(rollbackFor = Exception.class)
    public IResponse modifyLabel(@RequestParam("data") String jsonDataArrStr, @RequestParam("label") String label){
        String[] str=jsonDataArrStr.split(",");
        List contractNoList=new ArrayList();
        List contractAllList=new ArrayList();
        for(int i=0;i<str.length;i++){
            contractAllList.add(str[i]);
        }
        for(int i=0;i<contractAllList.size();i++) {
            String isLock = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>query().lambda()
                    .eq(CaseContractInfo::getContractNo, contractAllList.get(i)), false).getIsLock();
            if(!(isLock!=null && isLock.equals("yes"))){
                contractNoList.add(contractAllList.get(i));
            }
        }
        if(contractNoList.size() == 0){
            return IResponse.success("");
        }else {
            return IResponse.success(loanApproveTaskService.modifyLabel(contractNoList,label));
        }
    }

    @PostMapping("/loanDiscard")
    @ApiOperation("放款申请废弃")
    @Transactional(rollbackFor = Exception.class)
    public IResponse loanDiscard(@RequestParam("data") String jsonDataArrStr, @RequestParam("label") String label){
        String[] str=jsonDataArrStr.split(",");
        List contractNoList=new ArrayList();
        List contractAllList=new ArrayList();
        for(int i=0;i<str.length;i++){
            contractAllList.add(str[i]);
        }
        for(int i=0;i<contractAllList.size();i++) {
            LoanActivatePool pool = loanActivateService.getOne(Wrappers.<LoanActivatePool>query().lambda()
                    .eq(LoanActivatePool::getContractNo,contractAllList.get(i)));
            if (null != pool && null != pool.getContractActivateFlag()) {
                //如果收到合同激活落库通知则不提交流程
                throw new AfsBaseException("已激活数据不可执行废弃操作...");
            }
            if(ObjectUtils.isNotEmpty(pool)){
                pool.setLoanApproveStatus(ApplyStatusEnum.LOAN_DISCARD.getState());
                pool.setActStatus(ActivateStatusEnum.DISCARD.getStatus());
                loanActivateService.updateById(pool);
            }
            try{
                //修改合同状态
                CaseContractInfo caseContractInfo = caseContractInfoService.getOne(Wrappers.<CaseContractInfo>lambdaUpdate()
                        .eq(CaseContractInfo::getContractNo,contractAllList.get(i)));
                caseContractInfo.setApplyStatus(ApplyStatusEnum.LOAN_DISCARD.getState());
                caseContractInfo.setBusinessStage(BusinessStageEnum.LOAN_DISCARD.getCode());
                caseContractInfo.setContractStatus(ContractStatusEnum.contractCancel);
                caseContractInfoService.updateById(caseContractInfo);
                //记录合同取消日志
                    CaseApproveRecord lockOprRecord = new CaseApproveRecord();
                    lockOprRecord.setContractNo(caseContractInfo.getContractNo());
                    lockOprRecord.setUseScene(UseSceneEnum.GENERAL_LOAN.getValue());
                    lockOprRecord.setApproveSuggest(ApplyStatusEnum.LOAN_DISCARD.getState());
                    lockOprRecord.setApproveSuggestName("合同取消");
                    lockOprRecord.setApproveStartTime(new Date());
                    lockOprRecord.setApproveEndTime(new Date());
                    lockOprRecord.setDisposeStaff(SecurityUtils.getUser().getUserRealName());
                    lockOprRecord.setApproveType(ApproveTypeEnum.CANAEL.getValue());
                    caseApproveRecordService.save(lockOprRecord);
                //废弃信息通知进件系统
                approveLoanInfoService.sendToApplyNotic(caseContractInfo.getContractNo(),ApplyStatusEnum.LOAN_DISCARD);
                //结束工作流
                loanWorkflowService.giveUpWorkflow(caseContractInfo.getContractNo(), LoanProcessTypeEnum.GENERAL_LOAN.getCode());
                // 放款流程结束触发玄武反欺诈
                caseTortoiseService.safeSignalFraudHand(caseContractInfo.getApplyNo(), GwtTortoiseAntiFraudCallStep.AFTER_LOAN_APPLY_END);
            }catch (Exception e){
                log.info("执行废弃操作失败！",e);
            }
        }
        return IResponse.success("");
    }

    @PostMapping(value = "/getLoanCommonTaskList")
    @ApiOperation(value = "多条件分页获取待审核任务--仅展示当前登录用户的待审核任务，组长可以查看本组")
    public IResponse<IPage<ApproveTaskVo>> getLoanCommonTaskList(@RequestBody LoanApproveTaskCondition condition) {

        //流程类型条件
        List processList = new ArrayList();
        processList.add(LoanProcessTypeEnum.GENERAL_LOAN.getCode());
        processList.add(LoanProcessTypeEnum.LOAN_REPAIR.getCode());
        processList.add(LoanProcessTypeEnum.FLAW_UPDATE.getCode());
        processList.add(LoanProcessTypeEnum.INSPECTION.getCode());
        condition.setProcessTypeList(processList);
        //获取标签Id
        String str = condition.getTag();
        List labelIdList = new ArrayList();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(str)) {
            String[] labelId = str.split(",");
            for (int i = 0; i < labelId.length; i++) {
                Console.log(labelId[i]);
                labelIdList.add(labelId[i]);
            }
        }
        if (labelIdList != null && labelIdList.size() > 0) {
            condition.setLabelList(labelIdList);
        }
        if(condition.getStartDate()!=null){
            LocalDateTime startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getStartDate().getTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getEndDate().getTime()), ZoneId.systemDefault());
            //获取最小时间 xxxx-xx-xx 0:00:00
            LocalDateTime startOfDay = startTime.with(LocalTime.MIN);
            log.info("获取范围最小时间{}",startOfDay);
            //获取30天前最大时间 xxxx-xx-xx 23:59:59
            LocalDateTime endOfDay = endTime.with(LocalTime.MAX);
            log.info("获取范围最大时间{}",endOfDay);
            condition.setStartDate(Date.from(startOfDay.atZone( ZoneId.systemDefault()).toInstant()));
            condition.setEndDate(Date.from(endOfDay.atZone( ZoneId.systemDefault()).toInstant()));
        }
        IPage<LoanApproveTaskVO> pageResult = loanApproveTaskService.queryCommonPoolTaskList(
                new Page(condition.getPageNumber(), condition.getPageSize()),
                condition);

        pageResult.getRecords().forEach(approveTaskVo -> {
            /**案件基础信息*/
            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo, approveTaskVo.getApplyNo()));
            /**车辆信息*/
            CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda()
                    .eq(CaseCarInfo::getApplyNo, approveTaskVo.getApplyNo()));

            CaseApproveRecord caseApproveRecord = caseApproveRecordService.getOne(Wrappers.<CaseApproveRecord>query().lambda()
                    .eq(CaseApproveRecord::getDisposeStaff, approveTaskVo.getApplyNo()));

            if (ObjectUtils.isNotEmpty(caseApproveRecord)) {
                approveTaskVo.setDisposeStaff(caseApproveRecord.getDisposeStaff());
            }

            if (ObjectUtils.isNotEmpty(caseBaseInfo)) {
                // 当前时间，毫秒
                Long nowMilliSeconds = System.currentTimeMillis();
                // 开始时间，毫秒
                Long submitDateMilliSeconds = approveTaskVo.getStartTime().getTime();
                Long effectTimeReckon = caseBaseInfo.getEffectTimeReckon();
                int seconds = Convert.toInt((effectTimeReckon + nowMilliSeconds - submitDateMilliSeconds) / 1000, 0);
                String hour = org.apache.commons.lang3.StringUtils.leftPad(seconds / 3600 + "", 2, '0');
                String minute = org.apache.commons.lang3.StringUtils.leftPad((seconds % 3600) / 60 + "", 2, '0');
                String second = org.apache.commons.lang3.StringUtils.leftPad((seconds % 3600) % 60 + "", 2, '0');
                // 拼接车辆信息显示
            }
            if (Objects.nonNull(caseCarInfo)) {
                approveTaskVo.setCarName(caseCarInfo.getBrandName() + caseCarInfo.getModelName());
            }
            /**  标签信息 **/
            List<LoanLabelInfo> labelList = loanLabelInfoService.list(Wrappers.<LoanLabelInfo>query().lambda()
                    .eq(LoanLabelInfo::getApplyNo, approveTaskVo.getApplyNo())
                    .eq(LoanLabelInfo::getContractNo, approveTaskVo.getContractNo()));
            approveTaskVo.setLabelList(labelList);
        });
        return IResponse.success(pageResult);

    }

    @PostMapping(value = "/getLoanWaitReviewTaskList")
    @ApiOperation(value = "多条件分页获取待复核任务")
    public IResponse<IPage<ApproveTaskVo>> getLoanWaitReviewTaskList(@RequestBody LoanApproveTaskCondition condition) {

        //流程类型条件
        List processList = new ArrayList();
        List applyStatusList =new ArrayList();
        processList.add(LoanProcessTypeEnum.GENERAL_LOAN.getCode());
        processList.add(LoanProcessTypeEnum.LOAN_REPAIR.getCode());
        applyStatusList.add(ApplyStatusEnum.LOAN_WAIT_CONFIRM.getState());
        condition.setProcessTypeList(processList);
        condition.setApplyStatusList(applyStatusList);
        //获取标签Id
        String str = condition.getTag();
        List labelIdList = new ArrayList();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(str)) {
            String[] labelId = str.split(",");
            for (int i = 0; i < labelId.length; i++) {
                Console.log(labelId[i]);
                labelIdList.add(labelId[i]);
            }
        }
        if (labelIdList != null && labelIdList.size() > 0) {
            condition.setLabelList(labelIdList);
        }
        if(condition.getStartDate()!=null){
            LocalDateTime startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getStartDate().getTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getEndDate().getTime()), ZoneId.systemDefault());
            //获取最小时间 xxxx-xx-xx 0:00:00
            LocalDateTime startOfDay = startTime.with(LocalTime.MIN);
            log.info("获取范围最小时间{}",startOfDay);
            //获取30天前最大时间 xxxx-xx-xx 23:59:59
            LocalDateTime endOfDay = endTime.with(LocalTime.MAX);
            log.info("获取范围最大时间{}",endOfDay);
            condition.setStartDate(Date.from(startOfDay.atZone( ZoneId.systemDefault()).toInstant()));
            condition.setEndDate(Date.from(endOfDay.atZone( ZoneId.systemDefault()).toInstant()));
        }
        IPage<LoanApproveTaskVO> pageResult = loanApproveTaskService.queryWaitReviewPoolTaskList(
                new Page(condition.getPageNumber(), condition.getPageSize()),
                condition);

        pageResult.getRecords().forEach(approveTaskVo -> {
            /**案件基础信息*/
            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo, approveTaskVo.getApplyNo()));
            /**车辆信息*/
            CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda()
                    .eq(CaseCarInfo::getApplyNo, approveTaskVo.getApplyNo()));

            CaseApproveRecord caseApproveRecord = caseApproveRecordService.getOne(Wrappers.<CaseApproveRecord>query().lambda()
                    .eq(CaseApproveRecord::getDisposeStaff, approveTaskVo.getApplyNo()));

            if (ObjectUtils.isNotEmpty(caseApproveRecord)) {
                approveTaskVo.setDisposeStaff(caseApproveRecord.getDisposeStaff());
            }

            if (ObjectUtils.isNotEmpty(caseBaseInfo)) {
                // 当前时间，毫秒
                Long nowMilliSeconds = System.currentTimeMillis();
                // 开始时间，毫秒
                Long submitDateMilliSeconds = approveTaskVo.getStartTime().getTime();
                Long effectTimeReckon = caseBaseInfo.getEffectTimeReckon();
                int seconds = Convert.toInt((effectTimeReckon + nowMilliSeconds - submitDateMilliSeconds) / 1000, 0);
                String hour = org.apache.commons.lang3.StringUtils.leftPad(seconds / 3600 + "", 2, '0');
                String minute = org.apache.commons.lang3.StringUtils.leftPad((seconds % 3600) / 60 + "", 2, '0');
                String second = org.apache.commons.lang3.StringUtils.leftPad((seconds % 3600) % 60 + "", 2, '0');
                // 拼接车辆信息显示
            }
            if (Objects.nonNull(caseCarInfo)) {
                approveTaskVo.setCarName(caseCarInfo.getBrandName() + caseCarInfo.getModelName());
            }
            /**  标签信息 **/
            List<LoanLabelInfo> labelList = loanLabelInfoService.list(Wrappers.<LoanLabelInfo>query().lambda()
                    .eq(LoanLabelInfo::getApplyNo, approveTaskVo.getApplyNo())
                    .eq(LoanLabelInfo::getContractNo, approveTaskVo.getContractNo()));
            approveTaskVo.setLabelList(labelList);
        });
        return IResponse.success(pageResult);

    }

    /**
     * @Description 任务操作人变更
     * @Author rongji.zhang
     * @Date 2020/8/20 20:41
     */
    @PostMapping("/taskHandler")
//    @PreAuthorize("@pms.hasPermission('approve_handler_change')")
    public IResponse taskHandler(@RequestBody TaskHandlerChangeVO taskHandlerChangeVO) {
        return IResponse.success(loanApproveWorkflowService.reformist(NormalReformistVO.builder()
                .stageId(taskHandlerChangeVO.getStageId())
                .reformistUserName(taskHandlerChangeVO.getUserName())
                .reformistUserRealName(taskHandlerChangeVO.getUserRealName())
                .oriUserName(taskHandlerChangeVO.getOriUserName()).build()).getMessage());
    }

    /**
     * @Description 任务操作人批量变更
     * @Author rongji.zhang
     * @Date 2020/9/27 20:41
     */
    @PostMapping("/taskHandlerList")
//    @PreAuthorize("@pms.hasPermission('approve_handler_change')")
    public IResponse taskHandlerList(@RequestBody TaskHandlerChangeVO taskHandlerChangeVO) {
        try {
            if(CollectionUtils.isNotEmpty(taskHandlerChangeVO.getChangeOwnerParamList())){
                taskHandlerChangeVO.getChangeOwnerParamList().forEach(changeOwnerParam->{
                    loanApproveWorkflowService.reformist(NormalReformistVO.builder()
                            .stageId(changeOwnerParam.getStageId())
                            .reformistUserName(taskHandlerChangeVO.getUserName())
                            .reformistUserRealName(taskHandlerChangeVO.getUserRealName())
                            .oriUserName(changeOwnerParam.getApproveStaff()).build()).getMessage();
                });
            }
            return IResponse.success(true);
        }catch (Exception e){
            log.info("批量改派任务操作人失败！",e);
            return IResponse.fail("批量改派任务操作人失败！");
        }
    }

    @PostMapping(value = "/getLoanAllTaskList")
    @ApiOperation(value = "多条件分页获取所有案件信息")
    public IResponse<IPage<ApproveTaskVo>> getLoanAllTaskList(@RequestBody LoanApproveTaskCondition condition) {

        //流程类型条件
        List processList = new ArrayList();
        processList.add(LoanProcessTypeEnum.GENERAL_LOAN.getCode());
        processList.add(LoanProcessTypeEnum.LOAN_REPAIR.getCode());
        processList.add(LoanProcessTypeEnum.FLAW_UPDATE.getCode());
        processList.add(LoanProcessTypeEnum.INSPECTION.getCode());
        condition.setProcessTypeList(processList);
        //获取标签Id
        String str = condition.getTag();
        List labelIdList = new ArrayList();
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(str)) {
            String[] labelId = str.split(",");
            for (int i = 0; i < labelId.length; i++) {
                Console.log(labelId[i]);
                labelIdList.add(labelId[i]);
            }
        }
        if(condition.getStartDate()!=null){
            LocalDateTime startTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getStartDate().getTime()), ZoneId.systemDefault());
            LocalDateTime endTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(condition.getEndDate().getTime()), ZoneId.systemDefault());
            //获取最小时间 xxxx-xx-xx 0:00:00
            LocalDateTime startOfDay = startTime.with(LocalTime.MIN);
            log.info("获取范围最小时间{}",startOfDay);
            //获取30天前最大时间 xxxx-xx-xx 23:59:59
            LocalDateTime endOfDay = endTime.with(LocalTime.MAX);
            log.info("获取范围最大时间{}",endOfDay);
            condition.setStartDate(Date.from(startOfDay.atZone( ZoneId.systemDefault()).toInstant()));
            condition.setEndDate(Date.from(endOfDay.atZone( ZoneId.systemDefault()).toInstant()));
        }
        if (labelIdList != null && labelIdList.size() > 0) {
            condition.setLabelList(labelIdList);
        }
        IPage<LoanApproveTaskVO> pageResult = loanApproveTaskService.queryAllPoolTaskList(
                new Page(condition.getPageNumber(), condition.getPageSize()),
                condition);

        pageResult.getRecords().forEach(approveTaskVo -> {
            /**案件基础信息*/
            CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                    .eq(CaseBaseInfo::getApplyNo, approveTaskVo.getApplyNo()));
            /**车辆信息*/
            CaseCarInfo caseCarInfo = caseCarInfoService.getOne(Wrappers.<CaseCarInfo>query().lambda()
                    .eq(CaseCarInfo::getApplyNo, approveTaskVo.getApplyNo()));
            /**合作商信息*/
            CaseChannelInfo caseChannelInfo =caseChannelInfoService.getOne(Wrappers.<CaseChannelInfo>query().lambda()
                    .eq(CaseChannelInfo::getApplyNo,approveTaskVo.getApplyNo()));
            CaseApproveRecord caseApproveRecord = caseApproveRecordService.getOne(Wrappers.<CaseApproveRecord>query().lambda()
                    .eq(CaseApproveRecord::getDisposeStaff, approveTaskVo.getApplyNo()));

            if (ObjectUtils.isNotEmpty(caseApproveRecord)) {
                approveTaskVo.setDisposeStaff(caseApproveRecord.getDisposeStaff());
            }

            if (ObjectUtils.isNotEmpty(caseBaseInfo) && approveTaskVo.getStartTime()!=null) {
                // 当前时间，毫秒
                Long nowMilliSeconds = System.currentTimeMillis();
                // 开始时间，毫秒
                Long submitDateMilliSeconds = approveTaskVo.getStartTime().getTime();
                Long effectTimeReckon = caseBaseInfo.getEffectTimeReckon();
                int seconds = Convert.toInt((effectTimeReckon + nowMilliSeconds - submitDateMilliSeconds) / 1000, 0);
                String hour = org.apache.commons.lang3.StringUtils.leftPad(seconds / 3600 + "", 2, '0');
                String minute = org.apache.commons.lang3.StringUtils.leftPad((seconds % 3600) / 60 + "", 2, '0');
                String second = org.apache.commons.lang3.StringUtils.leftPad((seconds % 3600) % 60 + "", 2, '0');
                // 拼接车辆信息显示
            }
            if (Objects.nonNull(caseCarInfo)) {
                approveTaskVo.setCarName(caseCarInfo.getBrandName() + caseCarInfo.getModelName());
            }
            /**  标签信息 **/
            List<LoanLabelInfo> labelList = loanLabelInfoService.list(Wrappers.<LoanLabelInfo>query().lambda()
                    .eq(LoanLabelInfo::getApplyNo, approveTaskVo.getApplyNo())
                    .eq(LoanLabelInfo::getContractNo, approveTaskVo.getContractNo()));
            approveTaskVo.setLabelList(labelList);
            if(ObjectUtils.isNotEmpty(caseChannelInfo)){
                approveTaskVo.setDealerName(caseChannelInfo.getDealerName());
            }
            //当合同号码和案件状态同时为空，显示案件状态为放款待提交
            if(StringUtils.isBlank(approveTaskVo.getContractNo())&&StringUtils.isBlank(approveTaskVo.getApplyStatus())) {
                approveTaskVo.setApplyStatus(ApplyStatusEnum.LOAN_WAIT_SUBMIT.getState());
            }
        });
        return IResponse.success(pageResult);

    }

    @PostMapping("/getLabelList")
    @ApiOperation("获取案件标签列表")
    public IResponse getLabelList() {
        List<LoanLabelInfo> labelList = loanLabelInfoService.getLabelList();
        return IResponse.success(labelList);
    }

    @PostMapping("/getBrandNameList")
    @ApiOperation("获取车辆品牌列表")
    public IResponse getBrandName() {
        List<LoanApproveTaskVO> brandNameList = loanLabelInfoService.getBrandNameList();
        return IResponse.success(brandNameList);
    }

    @PostMapping("/getConfCaseLabelList")
    @ApiOperation("获取标签库")
    public IResponse getConfCaseLabelList() {
        List<ManualLabel> list = manualLabelService.list(Wrappers.<ManualLabel>query().lambda().eq(ManualLabel::getLabelPhase,LabelPhaseEnum.CREDITADUIT));
        return IResponse.success(list);
    }

}
